{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 混合高斯分布(Gaussian Mixture Model, GMM) 的实现\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.mixture import GaussianMixture"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预测类别: [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
      " 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 2 0 2 0 2\n",
      " 2 2 2 0 2 2 2 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0 0 0\n",
      " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      " 0 0]\n",
      "均值: [[6.54639415 2.94946365 5.48364578 1.98726565]\n",
      " [5.006      3.428      1.462      0.246     ]\n",
      " [5.9170732  2.77804839 4.20540364 1.29848217]]\n",
      "方差: [[[0.38744093 0.09223276 0.30244302 0.06087397]\n",
      "  [0.09223276 0.11040914 0.08385112 0.05574334]\n",
      "  [0.30244302 0.08385112 0.32589574 0.07276776]\n",
      "  [0.06087397 0.05574334 0.07276776 0.08484505]]\n",
      "\n",
      " [[0.121765   0.097232   0.016028   0.010124  ]\n",
      "  [0.097232   0.140817   0.011464   0.009112  ]\n",
      "  [0.016028   0.011464   0.029557   0.005948  ]\n",
      "  [0.010124   0.009112   0.005948   0.010885  ]]\n",
      "\n",
      " [[0.2755171  0.09662295 0.18547072 0.05478901]\n",
      "  [0.09662295 0.09255152 0.09103431 0.04299899]\n",
      "  [0.18547072 0.09103431 0.20235849 0.06171383]\n",
      "  [0.05478901 0.04299899 0.06171383 0.03233775]]]\n"
     ]
    }
   ],
   "source": [
    "data = load_iris() # 加载鸢尾花数据集\n",
    "n_components = 3  # 高斯分布的数量\n",
    "model = GaussianMixture(n_components=n_components) # 创建GMM模型\n",
    "model.fit(data.data) # 训练模型\n",
    "print(\"预测类别:\",model.predict(data.data))  # 预测类别\n",
    "print(\"均值:\",model.means_)  # 各高斯分布的均值\n",
    "print(\"方差:\",model.covariances_)  # 各高斯分布的方差"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
